﻿@page "/"
@rendermode InteractiveServer
@inject ISnackbar Snackbar;
@inject NavigationManager Navigation
@inject IClientWorker _clientWorker

<PageTitle>@AppData.AppConfig.AppName</PageTitle>

    @if (switchs == null)
{
    <MudProgressCircular Color="Color.Default" Indeterminate="true" />
}
else
{
    <MudPaper Class="d-flex flex-wrap gap-0" Elevation="0" Square="true">
        @foreach (var item in switchs)
        {
            <MudPaper Width="50%" Elevation="0" Style="max-width:200px;" Square="true">
                <MudCard Outlined="true" Style="margin:10px;" Elevation="2">
                    <MudCardMedia Image="@GetImage(item)" Height="80" />
                    <MudCardActions>
                        <MudFab StartIcon="@Icons.Material.Filled.PowerSettingsNew" Color="@GetPower(item.Status)" Label="@item.Name" Disabled="@GetActive(item.Status)" DisableElevation="true" Size="Size.Small" Style="width:100%" OnClick="async()=>{await PowerClick(item);}" />
                    </MudCardActions>
                    </MudCard>
                </MudPaper>
        }
        <MudPaper Width="50%" Elevation="0" Style="max-width:200px;" Square="true">
            <MudCard Outlined="true" Style="margin:10px;" Elevation="2">
                <MudCardMedia Image="images/login.jpg" Height="80" />
                <MudCardActions>
                    <MudFab StartIcon="@Icons.Material.Filled.PowerSettingsNew" Color="Color.Error" Label="@AppData.AppConfig.AppName" Disabled="false" DisableElevation="true" Size="Size.Small" Style="width:100%" OnClick="SignoutAsync" />
                </MudCardActions>
                </MudCard>
            </MudPaper>
        </MudPaper>
}

@code {
    [Inject] IAuthenticationService? AuthenticationService { get; set; }
    public bool _expanded;

    public bool IsConnected =>
        AppData.HUB?.State == HubConnectionState.Connected;

    private Color GetPower(SwitchDeviceStatus status)
    {
        return status == SwitchDeviceStatus.On ? Color.Primary : Color.Default;
    }

    private bool GetActive(SwitchDeviceStatus status)
    {
        return !(status == SwitchDeviceStatus.On || status == SwitchDeviceStatus.Off);
    }

    private string GetImage(SwitchDevice sd)
    {
        return $"images/{sd.SNID}.jpg";
    }

    private List<SwitchDevice>? switchs;
    private void GetSwitchs()
    {
        switchs = AppData.AppConfig.Switchs;
    }

    private void ConnectHub()
    {
        AppData.HUB?.On<string>("ReceiveResponse", OnReceiveResponse);
    }

    private void OnReceiveResponse(string message)
    {
        GetSwitchs();
        InvokeAsync(StateHasChanged);
        Snackbar.Add(message, Severity.Success);
    }

    private void MoreClick()
    {
        _expanded = !_expanded;
    }

    private async Task PowerClick(SwitchDevice s)
    {
        var state = s.Status == SwitchDeviceStatus.On ? "0" : "1";
        Snackbar.Add(s.DeviceMAC, Severity.Success);
        await _clientWorker.PublishAsync(MQTTTOPIC.CONTROL, new MQTTMessage() { Msg = state, To = s.DeviceMAC, GPIO = s.GPIO });
        await _clientWorker.PublishAsync(MQTTTOPIC.CONTROL, new MQTTMessage() { Msg = "2", To = s.DeviceMAC, GPIO = s.GPIO });
    }

    protected override void OnInitialized()
    {
        base.OnInitialized();
        GetSwitchs();
        ConnectHub();
    }

    private async Task SignoutAsync()
    {
        try
        {
            await AuthenticationService!.SignOutAsync();
            Navigation.NavigateTo("/login", true);
        }
        catch (InvalidOperationException ex)
        {
            Snackbar?.Add(ex.Message, Severity.Error);
        }
    }
}
